import { userState } from "./userReducer";
import axios from "axios";
import { ThunkAction } from "redux-thunk";
import { RootState } from "..";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";

interface LoginSuccess {
  type: typeof LOGIN_SUCCESS;
  payload: userState;
}

export function loginSuccess(payload: userState): LoginSuccess {
  return { type: LOGIN_SUCCESS, payload };
}

interface LoginFail {
  type: typeof LOGIN_FAIL;
}

export function loginFail(): LoginFail {
  return { type: LOGIN_FAIL };
}

export function login(loginData: {
  username: string;
  password: string;
}): ThunkAction<Promise<void>, RootState, any, userAction> {
  return async (dispatch) => {
    const resp = await axios.post("/api/login", loginData);
    const { code, message, data } = resp.data;
    if (code === 200) {
      dispatch(
        loginSuccess({
          username: data.username,
          nickname: data.nickname,
          isLogin: true,
          token: data.token,
        })
      );
      alert(message);
    } else {
      dispatch(loginFail());
      alert(message);
    }
  };
}

export type userAction = LoginSuccess | LoginFail;
